package com.gtw.modules.wx;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import com.foxinmy.weixin4j.mp.model.User;
import com.gtw.common.utils.R;
import com.gtw.common.utils.WeiXinMsgUtil;
import com.gtw.modules.api.service.TbTokenService;
import com.gtw.modules.api.service.TbUserService;
import com.gtw.modules.entity.TbDataInfo;
import com.gtw.modules.entity.TbUser;
import com.gtw.modules.sys.service.SysDataInfoService;
import com.gtw.utils.UidUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权后的回调请求处理
 * Created by wuye on 2018/3/5.
 */
@Controller
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbTokenService tbTokenService;

    @Autowired
    private SysDataInfoService sysDataInfoService;
    @Autowired private WeixinProxy weixinProxy;
    private Logger logger= LoggerFactory.getLogger(OAuthController.class);

    @GetMapping("/auth")
    public String doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, WeixinException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 用户同意授权后，能获取到code
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        Map<String, Object> map = new HashMap<>();
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            logger.info("收到微信code为:"+code);
            OauthToken authorizationToken = weixinProxy.getOauthApi().getAuthorizationToken(code);
            User weixinUser = weixinProxy.getOauthApi().getAuthorizationUser(authorizationToken);

            TbUser tbUser = tbUserService.queryOpenId(weixinUser.getOpenId());
            //使用openid判断是否注册
            if (tbUser == null) {
                //未注册，注册
                tbUser=new TbUser(weixinUser);
                TbDataInfo tbDataInfo = sysDataInfoService.queryObject(1);
                tbUser.setWithdrawaltimes(tbDataInfo.getDate());
                Integer parentId = Integer.valueOf(state);
                TbUser parent = tbUserService.queryById(parentId);
                if (parent == null) {
                    tbUser.setParentid(1);
                    tbUserService.add(tbUser);
                } else {
                    if (parent.getType() == 0) {
                        tbUser.setParentid(1);
                        tbUserService.add(tbUser);
                    } else {
                        tbUser.setParentid(parentId);
                        bindParend(tbUser,parent);
                    }
                }
            } else {
                //注册则更新资料
                tbUser.setProfileimageurl(weixinUser.getHeadimgurl());
                tbUser.setNickname(weixinUser.getNickName());
                tbUser.setSex(weixinUser.getGender() == 1 ? true : false);
                tbUser.setUsername(weixinUser.getNickName());
                tbUserService.update(tbUser);
            }
            map = tbTokenService.createToken(tbUser.getUserId());
            // 设置要传递的参数
        }
        // 跳转到index.jsp
//         request.getRequestDispatcher("www.guangtouboy.com").forward(request, response);
//        ModelAndView view = new ModelAndView("redirect:http://www.guangtouboy.com/#/Login?token=" + map.get("token").toString());
//        view.addObject("state",state);
//        return view;
        return "redirect:http://jss.youwenyuedu.com/#/Login?state=" + state + "&token=" + map.get("token").toString();
    }

    /**
     * 绑定上下级关系,
     * @param tbUser
     * @param parent
     */
    private void bindParend(TbUser tbUser, TbUser parent) {

        if (tbUser.getUserId()==null){
            tbUserService.add(tbUser);
        }
        WeiXinMsgUtil.tuanduifensi(parent.getWxopenid(),String.valueOf(tbUser.getUserId()),tbUser.getUsername());
        if (tbUserService.queryById(parent.getParentid()) != null) {
            TbUser user2 = tbUserService.queryById(parent.getParentid());
            WeiXinMsgUtil.tuanduifensi(user2.getWxopenid(),String.valueOf(tbUser.getUserId()),tbUser.getUsername());
            tbUser.setParentid2(user2.getUserId());
            if (tbUserService.queryById(user2.getParentid()) != null) {
                TbUser user3 = tbUserService.queryById(user2.getParentid());
                tbUser.setParentid3(user3.getUserId());
                if (tbUserService.queryById(user3.getParentid()) != null) {
                    TbUser user4 = tbUserService.queryById(user3.getParentid());
                    tbUser.setParentid4(user4.getUserId());
                }
            }
        }
        tbUserService.update(tbUser);
    }
}
